<?php
namespace StarCloud\Library\Sms;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use Phalcon\Di;

class AliyunSmsClient extends AbstractSmsClient
{
    protected $accessKeyId;
    protected $accessKeySecret;
    protected $smsClient = null;

    public function __construct($config)
    {
        isset($config['accessKeyId']) && $this->accessKeyId = $config['accessKeyId'];
        isset($config['accessKeySecret']) && $this->accessKeySecret = $config['accessKeySecret'];

        $config = new Config([
            "accessKeyId" => $this->accessKeyId,
            "accessKeySecret" => $this->accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";
        $this->smsClient = new Dysmsapi($config);
    }

    public function sendCode($phone, $signName, $templateCode, $templateParam)
    {
        $requestParams = [
            "signName" => $signName,
            "templateCode" => $templateCode,
            "phoneNumbers" => $phone,
            "templateParam" => json_encode($templateParam),
        ];
        $sendSmsRequest = new SendSmsRequest($requestParams);
        // 复制代码运行请自行打印 API 的返回值
        $result = $this->smsClient->sendSms($sendSmsRequest);

        $response =  $result->body->toMap();

        Di::getDefault()->get('logger')->info(
            __CLASS__ . '::' . __FUNCTION__
            . " request is :" . json_encode($requestParams)
            . ' response is' . json_encode($response)
        );

        return $response;
    }
}
